$(function () {
  // var userInfo = JSON.parse(localStorage.getItem("logInfo"));
  // $(".top .userInfo").html(userInfo.login);
  var MorepayArr = []; //多种支付方式
  var pay_tableid = "";
  var curTable = "";
  if (location.search) {
    pay_tableid = location.search.split("?")[1].split("=")[1];
  }

  if (pay_tableid) {
    var table_info = {
      table_id: pay_tableid,
    }
    App.ajax("ss_wx/table_order_details", "post", {
      table_id: pay_tableid
    }, function (res) {
      if (res.flag == true) {
        table_info.order_id = res.order_detail.order_id;
        table_info.origin_reference = res.order_detail.origin_reference;
        table_info.m_date = res.order_detail.m_date;
        table_info.f_date = res.order_detail.m_date;
        table_info.name = res.table_name;
        var totalnum = 0;
        res.order_detail.pay_info.forEach(function (a, b) {
          totalnum += a.num;
          a.rsta = 1;
          a.ZFname = "";
          a.ZFprice = 0;
          if (a.cuisine && a.cuisine.length > 0) {
            a.cuisine.forEach(function (y, z) {
              a.ZFname += y.name + " ";
              a.ZFprice += y.price * 1;
            });
          }
          // a.ZFname = a.cuisine && a.cuisine.length > 0 ? a.cuisine[0].name : "";
          // a.ZFid = a.cuisine && a.cuisine.length > 0 ? a.cuisine[0].id : "";
          // a.ZFprice = a.cuisine && a.cuisine.length > 0 ? a.cuisine[0].price : "";
          if (a.combo_details && a.combo_details.length > 0) {
            var tcprice = 0;
            a.combo_details.forEach(function (m, n) {
              m.menu_list.forEach(function (a, b) {
                tcprice += (a.price * a.select_num);
                if (m.category_leixing == "客人自选") {
                  a.choosedNum = a.select_num
                }
              })
            });
            if (!a.extend_combo_flag) {
              a.price = tcprice;
            }
          }
          a.combo_details = a.combo_details && a.combo_details.length > 0 ? a.combo_details : "";
          a.combo_details1 = a.combo_details && a.combo_details.length > 0 ? a.combo_details : "";
        })

        table_info.totalInfo = {
          totalCount: totalnum,
          totalMon: res.order_detail.p_total
        };

        table_info.cart = res.order_detail.pay_info;
        curTable = table_info;
        //获取订单金额 桌台号

        $(".bill .tNum").html("桌台：" + curTable.name);
        $("#billMon,#receivMon").html((curTable.totalInfo.totalMon * 1).toFixed(2));
        $("#inputMon").val(curTable.totalInfo.totalMon * 1);
        localStorage.setItem("curTable", JSON.stringify(table_info));

        // tableInfos.push(table_info);
        // localStorage.setItem("tableInfos", JSON.stringify(tableInfos));

      } else {
        App.msg(res.msg);
      }
      if (!res.TokenTrue) {
        App.msg("Token失效，即将跳转到登录页面", function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })
  } else {
    curTable = JSON.parse(localStorage.getItem("curTable"));
    $(".bill .tNum").html("桌台：" + curTable.name);
    $("#billMon,#receivMon").html((curTable.totalInfo.totalMon * 1).toFixed(2));
    $("#inputMon").val(curTable.totalInfo.totalMon * 1);
  }
  var payCode = localStorage.getItem("payCode");
  //点击返回
  $(".Cashier .title .left").on("click", function () {
    history.go(-1);
  });

  $(".loadclose").off("click").on("click", function () {
    $('#loading').modal('hide');
    $('#membercharge').modal('hide');
  });

  $(".membercenter").off("click").on("click", function () {
    $('#loading').modal('hide');
    $('#membercharge').modal('show');
  });

  //获取支付方式
  App.ajax("ss_wx/pay_methods", "post", {}, function (res) {
    if (res.flag == true) {
      var payHtml = '<li class="' + (payCode ? (payCode == "SMZF" ? "active" : ""): "active") +
          '" data-paytype=\'{"name":"扫码支付","code":"SMZF","id":0,"type":"bank"}\'>' +
          '<i class="iconfont icon-saomafu" style="font-size:20px;"></i>扫码支付</li>';
      $.each(res.info, function (i, v) {
        // (i == 0 ? "active" : "")
        payHtml += '<li class="' + (payCode ? (v.code == payCode ? "active" : "") : "") + '" data-paytype=\'' + JSON.stringify(v) + '\'>';
        if (v.code == "ZFBZF") {
          payHtml += '<i class="iconfont icon-swiftpass_alipay_scan"></i>';
        } else if (v.code == "WXZF") {
          payHtml += '<i class="iconfont icon-weixinzhifu-"></i>';
        } else if (v.code == "YHKZF") {
          payHtml += '<i class="iconfont icon-yinhangqiazhifu"></i>';
        } else if (v.code == "VIPPA") {
          payHtml += '<i class="iconfont icon-huiyuanzhongxin" style="font-size:20px;color:gold;font-weight:600;"></i>'
        } else {
          payHtml += '<i class="iconfont icon-xianjinzhifu"></i>';
        }
        payHtml += v.name + '</li>';
      })
      $(".Cashier .payLists ul").html(payHtml);
      var actCode = $(".Cashier .payLists ul li.active").data("paytype").code;

      if (actCode == "TSCH") {
        $(".ZLMon").removeClass("hidden");
        $("#inputMon").focus();
        $(".FKMInput,.HYZHInput,.ZFMMInput,.GZZFInput").addClass("hidden");
      } else if (actCode == "YHKZF") {
        $(".ZLMon,.FKMInput,.HYZHInput,.ZFMMInput").addClass("hidden");
        $("#inputMon").focus();
      } else if (actCode == "VIPPA") {
        $(".HYZHInput,.ZFMMInput").removeClass("hidden");
        $(".ZLMon,.FKMInput").addClass("hidden");
        $(".HYZHInput #member_id").focus();
      } else if (actCode == "SMZF") {
        $(".FKMInput").removeClass("hidden");
        $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
        $(".FKMInput input").focus();
      }
      /*  else if (actCode == "WXZF") {
         $(".FKMInput").removeClass("hidden");
         $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
         $(".FKMInput input").focus();
       } else if (actCode == "ZFBZF") {
         $(".FKMInput").removeClass("hidden");
         $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
         $(".FKMInput input").focus();
       }  */
      else {
        $(".ZLMon").addClass("hidden");
        $(".FKMInput,.HYZHInput,.ZFMMInput").addClass("hidden");
        $("#inputMon").focus();
      }
    } else {
      App.msg(res.msg);
    }
    if (!res.TokenTrue) {
      App.msg("Token失效，即将跳转到登录页面", function () {
        setTimeout(function () {
          location.href = "../login.html";
        }, 1000)
      })
    }
  })

  //点击搜索优惠券
  $(".searCoupon").off("click").on("click", function () {
    // 订单金额
    var billMon = $("#billMon").html() * 1;
    if (MorepayArr.length > 0) {
      MorepayArr = [];
      $(".ZFBZ").addClass("hidden");
      $(".ZFBZ .ZFCon").html("");
      $("#receivMon").html((billMon * 1).toFixed(2));
      $("#inputMon").val((billMon * 1).toFixed(2));
    }
    $(".vipCount").addClass('hidden');

    var discount = $("#Discount").val();
    if (discount != "") {
      App.msg("折扣和优惠券不能叠加使用");
    } else {
      var HXcode = $("#HXcode").val();
      if (HXcode == "") {
        App.msg("请输入核销码");
      } else {
        App.ajax("ss_wx/CardInfo", "post", {
          code: HXcode
        }, function (res) {
          if (res.flag == true) {
            var card = res.card_details;
            var today = moment().valueOf();
            var end_date = moment(card.end_date).valueOf();
            if (today <= end_date) {

              if (card.discount_type == "dis") {
                $("#yhMon").html((billMon * (1 - card.discount / 100)).toFixed(2))
                $(".yhMon").removeClass("hidden");
                $("#receivMon").html((billMon * (card.discount / 100)).toFixed(2));
                $("#inputMon").val((billMon * (card.discount / 100)).toFixed(2));
              } else if (card.discount_type == "pri") {
                $("#yhMon").html((card.discount * 1).toFixed(2));
                $(".yhMon").removeClass("hidden");
                if (billMon <= card.discount) {
                  $("#receivMon").html(0.00);
                  $("#inputMon").val(0);
                } else {
                  $("#receivMon").html((billMon - card.discount).toFixed(2));
                  $("#inputMon").val((billMon - card.discount).toFixed(2));
                }
              }
            }

            var couponHtml = "";
            couponHtml += '<div class="couponInfo" data-couponinfo=\'' + JSON.stringify(card) + '\'> <div class="name">' + card.name + '</div> <div class="content ' + (today > end_date ? "GQ" : "") + '"> <div class="left"> <span class="text">' + (card.discount_type == "dis" ? "折扣" : card.discount_type == "pri" ? "直减" : "减") + '</span> <span class="mon">' + card.discount + (card.discount_type == "dis" ? "%" : card.discount_type == "pri" ? "元" : "积分") + '</span> </div> <div class="right">' + (today > end_date ? "已过期" : card.state) + '</div> </div><div class="time">有效期：' + card.end_date + '<button class="btn btn-danger btn-sm deleCoupon">取消</button>' + '</div></div>';
            $(".showCoupon").html(couponHtml).removeClass("hidden");
          } else {
            App.msg(res.msg);
            if (!$(".showCoupon").hasClass("hidden")) {
              // var billMon = $("#billMon").html() * 1
              // $(".showCoupon").empty().addClass("hidden");
              // $("#yhMon").html("")
              // $(".yhMon").addClass("hidden");
              // $("#receivMon").html(billMon.toFixed(2));
              // $("#inputMon").val(billMon.toFixed(2));
              $(".deleCoupon").trigger("click");
            }
          }
          $("#HXcode").val("")
          if (!res.TokenTrue) {
            App.msg("Token失效，即将跳转到登录页面", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      }
    }

  })
  //点击取消优惠券
  $(".showCoupon").on("click", ".deleCoupon", function () {
    var billMon = $("#billMon").html() * 1
    $(".showCoupon").empty().addClass("hidden");
    $("#yhMon").html("")
    $(".yhMon").addClass("hidden");
    $("#receivMon").html(billMon.toFixed(2));
    $("#inputMon").val(billMon.toFixed(2));
  })

  // $(".saoma .FKM_je").val("￥" + curTable.totalInfo.totalMon * 1);
  //点击查看订单
  $(".Cashier .bill .checkMenu").on("click", function () {
    var menuHtml = "";
    $.each(curTable.cart, function (i, v) {
      menuHtml += "<li data-dishes=\'" + JSON.stringify(v) + "\'><span>" + v.name + (v.ZFname ? "<span style='color:#f40'> | " + v.ZFname + "</span>" : (v.combo_details && v.combo_details.length > 0 ? "<a style='margin-left:8px;' class='btn btn-sm btn-warning btn-details' data-toggle='popover' >套餐详情</a>" : "")) + "</span><span>" + (pay_tableid ? v.price * 1 : (v.combo_details && v.combo_details.length > 0 ? v.totalTCPrice : v.cuisine && v.cuisine.length > 0 ? (v.price * 1 + (v.ZFprice ? v.ZFprice * 1 : 0)) : v.price)).toFixed(2) + "</span><span>" + (v.num * 1).toFixed(2) + "</span><span>" + (pay_tableid ? (v.price * v.num) : (v.combo_details && v.combo_details.length > 0 ? v.totalTCPrice : v.cuisine && v.cuisine.length > 0 ? (v.price * 1 + (v.ZFprice ? v.ZFprice * 1 : 0)) : v.price) * v.num).toFixed(2) + "</span></li>"
    });
    $("#MenuModal .menuLists").html(menuHtml);
  })
  //点击套餐详情
  $("#MenuModal .menuLists").off("mouseover").on("mouseover", ".btn-details", function () {
    var dishes = $(this).parents("li").data("dishes");
    var content = "";
    var menu_list = [];
    dishes.combo_details1.forEach(function (x, y) {
      x.menu_list.forEach(function (a, b) {
        menu_list.push(a);
      })
    })
    menu_list.forEach(function (a, b) {
      content += b + 1 + "." + a.name + '---' + (a.choosedNum ? a.choosedNum : a.select_num) + a.uom + '---' + a.price + '元/' + a.uom + "<br/>"
    })
    $(this).popover({
      content: content,
      placement: "top",
      trigger: "click",
      html: true
    })
  });

  //输入折扣，改变应收金额
  $("#Discount").on("input", function () {
    $(".vipCount").addClass('hidden');
    MorepayArr = [];
    $(".ZFBZ").addClass("hidden");
    $(".ZFBZ .ZFCon").html("");
    var billMon = $("#billMon").html();
    var count = $("#Discount").val();
    if (!$(".showCoupon").hasClass("hidden")) {
      App.msg("折扣和优惠券不能叠加使用");
      $("#Discount").val("");
    } else {
      //改变应收金额
      if (count > 0) {
        $("#receivMon").html((billMon * (count / 100)).toFixed(2));
        $("#inputMon").val((billMon * (count / 100)).toFixed(2));
      } else {
        $("#receivMon").html((billMon * 1).toFixed(2));
        $("#inputMon").val((billMon * 1).toFixed(2));
      }
    }
  })
  //移动支付时输入折扣，改变应收金额
  // $("#DiscontMob input").on("input propertychange", function () {
  //   var billMon = $("#billMon").html();
  //   var nums = $("#DiscontMob input").val();
  //   console.log(nums);

  //   //改变应收金额
  //   if (nums) {
  //     $("#receivMon").html((billMon * (nums / 100)).toFixed(2));
  //     $(".saoma .FKM_je").val("￥" + (billMon * (nums / 100)).toFixed(2));
  //   } else {
  //     $("#receivMon").html((billMon * 1).toFixed(2));
  //     $(".saoma .FKM_je").val("￥" + (billMon * 1).toFixed(2));
  //   }
  // })
  // //获取折扣输入框的值
  // function getDiscount(id) {
  //   var inps = $(id).find('.num');
  //   var nums = "";
  //   inps.each(function (j, k) {
  //     nums += $(this).html();
  //   })
  //   return nums;
  // }
  //输入抹零金额，改变应收金额
  $("#MLJE").on("input", function () {
    var billMon = $("#billMon").html();
    var inps = $("#MLJE").find('.num');
    var nums = "";
    inps.each(function (j, k) {
      nums += $(this).html();
    })
    //改变应收金额
    $("#receivMon").html();
  })
  //抹零选项改变
  $("#MLRadio input").on("change", function () {
    if ($(this).prop("checked")) {
    };
  })

  //输入实收金额，改变找零金额
  $("#inputMon").on("input", function () {
    var inputMon = $("#inputMon").val();
    //获取应收金额
    var SSMon = $("#receivMon").html();
    var ZLMon = inputMon - SSMon;
    // if (ZLMon <=0) {
    //   return;
    // }
    //改变找零金额
    $("#ZLMon").html(ZLMon.toFixed(2))
  })


  //支付方式切换
  $(".payLists ul").on("click", "li", function () {
    var payType = $(this).data("paytype");
    $(this).addClass("active").siblings().removeClass("active");
    if (payType.code == "TSCH") {
      // $("#inputMon").focus();
      $(".ZLMon").removeClass("hidden");
      $(".FKMInput,.HYZHInput,.ZFMMInput").addClass("hidden");
    } else if (payType.code == "YHKZF") {
      // $("#inputMon").focus();
      $(".ZLMon,.FKMInput,.HYZHInput,.ZFMMInput").addClass("hidden");
    } else if (payType.code == "VIPPA") {
      $(".HYZHInput,.ZFMMInput").removeClass("hidden");
      $("#member_id").val("");
      $("#ZFMM").val("");
      $(".ZLMon,.FKMInput").addClass("hidden");
      // $(".HYZHInput input").focus();
    } else if (payType.code == "SMZF") {
      $(".FKMInput").removeClass("hidden");
      $(".FKMInput input").focus();
      $("#FKMInput").val("");
      $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
    }
    /* else if (payType.code == "WXZF") {
      $(".FKMInput").removeClass("hidden");
      $(".FKMInput input").focus();
      $("#FKMInput").val("");
      $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
    } else if (payType.code == "ZFBZF") {
      $(".FKMInput").removeClass("hidden");
      $(".FKMInput input").focus();
      $("#FKMInput").val("");
      $(".ZLMon,.HYZHInput,.ZFMMInput").addClass("hidden");
    }  */
    else {
      $("#inputMon").focus();
      $(".ZLMon").addClass("hidden");
      $(".FKMInput,.HYZHInput,.ZFMMInput").addClass("hidden");
    }

  });



  //多支付方式选择
  $(".payLists ul").off("dblclick").on("dblclick", "li", function () {
    var payType = $(this).data("paytype");
    $("#PayModal").modal();
    $("#PayModal .modal-title").html(payType.name);
    $('#PayModal').on('shown.bs.modal', function () {
      if (MorepayArr.length == 0) {
        $("#PayModal .pay-mon").val("").focus();
      } else {
        var filerPay = MorepayArr.filter(function (v, i) {
          return v.id == payType.id;
        })
        if (filerPay.length == 0) {
          $("#PayModal .pay-mon").val("").focus();
        } else {
          $("#PayModal .pay-mon").val(filerPay[0].money).focus();
        }
      }
    })
    // 点击多支付方式确认按钮
    $("#PayModal .btn-pay").off("click").on("click", function () {
      var val = $("#PayModal .pay-mon").val();
      var title = $("#PayModal .modal-title").html();
      //订单金额
      var billMon = $("#billMon").html();
      //应收金额
      var receivMon = $("#receivMon").html();
      //订单折扣
      var Discount = $("#Discount").val()
      if (val == "") {
        App.msg("请输入金额")
      } else if (val == 0) {
        if (MorepayArr.length == 0) return;
        MorepayArr = MorepayArr.filter(function (v, i) {
          return v.id != payType.id
        })
        var allPayMon1 = 0;
        $(".ZFBZ .ZFCon").html("");
        MorepayArr.forEach(function (v, i) {
          allPayMon1 += v.money * 1;
          $(".ZFBZ .ZFCon").removeClass("hidden").append(v.name + v.money + "元 ,");
        })
        $(".ZFBZ .ZFCon").append("<button class='clearPay'>清除</button>");

        if (MorepayArr.length == 0) {
          $(".ZFBZ").addClass("hidden");
        }
        $("#receivMon").html(((billMon * (Discount > 0 ? Discount / 100 : 1)) - allPayMon1).toFixed(2))
        $("#inputMon").val(((billMon * (Discount > 0 ? Discount / 100 : 1)) - allPayMon1).toFixed(2));
        $("#PayModal").modal('hide')
      } else {
        if (val * 1 > billMon * 1 || val * 1 > receivMon * 1) {
          App.msg('输入金额大于订单金额/应收金额')
        } else {
          payType.money = val;
          MorepayArr.push(payType);
          $(".ZFBZ").removeClass("hidden");
          var allPayMon = 0;
          $(".ZFBZ .ZFCon").html("");
          MorepayArr.forEach(function (v, i) {
            allPayMon += v.money * 1;
            $(".ZFBZ .ZFCon").removeClass("hidden").append(v.name + v.money + "元 ,");
          })
          $(".ZFBZ .ZFCon").append("<button class='clearPay'>清除</button>");
          $("#receivMon").html(((billMon * (Discount > 0 ? Discount / 100 : 1)) - allPayMon).toFixed(2))
          $("#inputMon").val(((billMon * (Discount > 0 ? Discount / 100 : 1)) - allPayMon).toFixed(2));
          $("#PayModal").modal('hide')
        }
      }
    })

  });
  //点击清除支付备注
  $(".ZFBZ .ZFCon ").off("click").on("click", ".clearPay", function () {
    //订单金额
    var billMon = $("#billMon").html();
    //应收金额
    var receivMon = $("#receivMon").html();
    //订单折扣
    var Discount = $("#Discount").val()
    MorepayArr = [];
    $(".ZFBZ").addClass("hidden");
    $("#receivMon").html(((billMon * (Discount > 0 ? Discount / 100 : 1))).toFixed(2))
    $("#inputMon").val(((billMon * (Discount > 0 ? Discount / 100 : 1))).toFixed(2));
  });

  //移动支付
  var flag_once = true;
  $(".board .checkOut").off("click").on("click", function () {
    $('#loading').modal('show');
    if (flag_once) {
      flag_once = false;
      var paytype = $(".Cashier .payLists ul li.active").data("paytype");
      var pay_info = [];
      curTable.cart.forEach(function (v, i) {
        var obj = {
          p_id: v.p_id,
          p_num: v.num,
          name: v.name,
          temporary_flag: v.temporary_flag,
          c_id: v.c_id,
          price: v.price,
          print: (v.print ? v.print : []),
          uom: v.uom,
          cuisine: v.tastes ? v.tastes : [],
          pnotes: '',
          sdnotes: '',
          local_printer: v.local_printer,
          printer_position: v.printer_position,
          active_sale_count: v.active_sale_count
        };
        if (v.combo_details && v.combo_details.length > 0) {
          obj.combo_details = v.combo_details1;
        } else {
          obj.combo_details = [];
        }

        pay_info.unshift(obj);
      });
      var order_id = "";
      var online_pay_flag = "";
      // if (payCode) {
      if (!curTable.order_id) {
        order_id = App.guid();
        online_pay_flag = 0;
      } else {
        order_id = curTable.order_id;
        online_pay_flag = 1;
      }
      var money = $("#receivMon").html() * 1;
      var card_details = "";
      if (!$(".showCoupon").hasClass("hidden")) {
        card_details = $(".showCoupon .couponInfo").data("couponinfo");
      }
      //预留扫码支付
      if (paytype.code == "SMZF") {
        var auth_code = $("#FKMInput").val();
        if (auth_code == "") {
          App.msg("请输入付款码");
          $('#loading').modal('hide');
          flag_once = true;
        } else {
          var paymethodname = '';
          var int_auth_code = auth_code.substr(0, 2);
          var wechat_code = '10,11,12,13,14,15';
          var alipay_code = '28';
          if (wechat_code.includes(int_auth_code)) {
            paymethodname = '微信支付';
          }
          if (alipay_code.includes(int_auth_code)) {
            paymethodname = '支付宝支付';
          }
          var pay_methods = [{
            "pay_id": paytype.id,
            "money": $("#inputMon").val(),
            'paymethodname': paymethodname
          }];
          if (MorepayArr.length > 0) {
            MorepayArr.forEach(function (v) {
              pay_methods.push({
                "pay_id": v.id,
                "money": v.money,
                'paymethodname': v.name
              })
            })
          }
          var wx_pos_order = {
            'money': money,
            "m_date": curTable.m_date,
            "f_date": curTable.f_date,
            'auth_code': auth_code,
            'shop_id': 1,
            'out_trade_no': order_id,
            'out_trade_no_extend': App.guid(),
            "product_name": "点餐菜品",
            "online_pay_flag": online_pay_flag,
            // "print_num": localStorage.getItem("print_num"),
            "pos_order": JSON.stringify({
              "order_id": order_id,
              'date_order': App.formatDateTime(new Date()),
              "origin_reference": curTable.origin_reference,
              "pay_method": pay_methods,
              "card_details": card_details,
              "discount": $("#Discount").val(),
              "need_to_pay": $("#receivMon").html(),
              "customer_pay": $("#receivMon").html(),
              "zhaoLing": "",
              "moling": "",
              "pay_info": pay_info,
              "p_total": curTable.totalInfo.totalMon,
              "floor_id": curTable.floor_id,
              "table_id": curTable.table_id,
              'table_name': curTable.name,
              "note": curTable.ZDBZ ? curTable.ZDBZ : "",
              "pay_note": $("#comment").val(),
            })
          };
          App.ajax("scanQrcodeOrder", "post", wx_pos_order, function (res) {
            flag_once = true;
            if (res.return_code == "SUCCESS") {
              localStorage.removeItem("tableInfos");
              localStorage.removeItem("curTable");
              localStorage.removeItem("payCode");
              wx_pos_order.order_sequence = res.order_sequence ? res.order_sequence : "";
              wx_pos_order.f_date = res.pay_date;
              App.msg("支付成功", function () {
                $('#loading').modal('hide');
                setTimeout(function () {
                  location.href = "../pages/Table.html";
                }, 1000);
              });
              window.samfeng.scanQrcodeOrder(JSON.stringify(wx_pos_order));
            } else {
              App.confirm(res.return_msg, function () {
                flag_once = true;
              });
            }
            if (!res.TokenTrue) {
              App.msg("Token失效，即将跳转到登录页面", function () {
                setTimeout(function () {
                  location.href = "../login.html";
                }, 1000)
              })
            }
          })
        }
      }
      if (paytype.code == "VIPPA") {
        if (!curTable.order_id) {
          var member_id = $("#member_id").val();
          var password = $("#ZFMM").val();
          if (member_id == "") {
            App.msg("请输入会员帐号");
          } else if (password == "") {
            App.msg("请输入支付密码");
          } else {
            var pay_methods = [{
              "pay_id": paytype.id,
              "money": $("#inputMon").val(),
              'paymethodname': '会员支付'
            }];
            if (MorepayArr.length > 0) {
              MorepayArr.forEach(function (v) {
                pay_methods.push({
                  "pay_id": v.id,
                  "money": v.money,
                  'paymethodname': v.name
                })
              })
            }
            var vip_pos_order = {
              "pay_flag": 1,
              "m_date": curTable.m_date,
              "f_date": curTable.f_date,
              "member_id": member_id,
              "password": password,
              // "print_num": localStorage.getItem("print_num"),
              "pos_order": JSON.stringify({
                "order_id": App.guid(),
                "origin_reference": curTable.origin_reference,
                "date_order": App.formatDateTime(new Date()),
                "pay_method": pay_methods,
                "card_details": card_details,
                "discount": $("#Discount").val(),
                "need_to_pay": $("#receivMon").html(),
                "customer_pay": $("#inputMon").val(),
                "moling": "",
                "pay_info": pay_info,
                "p_total": curTable.totalInfo.totalMon,
                "floor_id": curTable.floor_id,
                "table_id": curTable.table_id,
                "table_name": curTable.name,
                "note": curTable.ZDBZ ? curTable.ZDBZ : "",
                "pay_note": $("#comment").val(),
              })
            };
            App.ajax("ss_wx/hzg_orders_and_pay", "post", vip_pos_order, function (res) {
              flag_once = true;
              if (res.flag == true) {
                localStorage.removeItem("tableInfos");
                localStorage.removeItem("curTable");
                localStorage.removeItem("payCode");
                vip_pos_order.order_sequence = res.order_sequence ? res.order_sequence: "";
                App.msg("支付成功", function () {
                  $('#loading').modal('hide');
                  setTimeout(function () {
                    location.href = "../pages/Table.html";
                  }, 1000);
                })
                window.samfeng.VipPay(JSON.stringify(vip_pos_order));
              } else {
                $('.membercenter').removeClass('hidden');
                App.msg(res.msg);
              }
              if (!res.TokenTrue) {
                App.msg("Token失效，即将跳转到登录页面", function () {
                  setTimeout(function () {
                    location.href = "../login.html";
                  }, 1000)
                })
              }
            })
          }
        } else {
          var member_id = $("#member_id").val();
          var password = $("#ZFMM").val();
          if (member_id == "") {
            App.msg("请输入会员帐号");
          } else if (password == "") {
            App.msg("请输入支付密码");
          } else {
            var pay_methods1 = [{
              "pay_id": paytype.id,
              "money": $("#inputMon").val(),
              'paymethodname': '会员支付'
            }];
            if (MorepayArr.length > 0) {
              MorepayArr.forEach(function (v) {
                pay_methods1.push({
                  "pay_id": v.id,
                  "money": v.money,
                  'paymethodname': v.name
                })
              })
            }
            var vip_pos_order1 = {
              "pay_flag": 1,
              "m_date": curTable.m_date,
              "f_date": curTable.f_date,
              "member_id": $("#member_id").val(),
              "password": $("#ZFMM").val(),
              // "print_num": localStorage.getItem("print_num"),
              "pos_order": JSON.stringify({
                "order_id": curTable.order_id ? curTable.order_id : App.guid(),
                "origin_reference": curTable.origin_reference,
                "date_order": App.formatDateTime(new Date()),
                "pay_method": pay_methods1,
                "discount": $("#Discount").val(),
                "need_to_pay": $("#receivMon").html(),
                "customer_pay": $("#inputMon").val(),
                "moling": "",
                "pay_info": pay_info,
                "p_total": curTable.totalInfo.totalMon,
                "floor_id": curTable.floor_id,
                "table_id": curTable.table_id,
                "table_name": curTable.name,
                "note": curTable.ZDBZ ? curTable.ZDBZ : "",
                "pay_note": $("#comment").val(),
              })
            };
            App.ajax("ss_wx/hzg_orders_pay", "post", vip_pos_order1, function (res) {
              flag_once = true;
              if (res.flag == true) {
                localStorage.removeItem("tableInfos");
                localStorage.removeItem("curTable");
                localStorage.removeItem("payCode");
                vip_pos_order1.order_sequence = res.order_sequence ? res.order_sequence: "";
                App.msg("支付成功", function () {
                  $('#loading').modal('hide');
                  setTimeout(function () {
                    location.href = "../pages/Table.html";
                  }, 1000);
                })
                window.samfeng.VipPay(JSON.stringify(vip_pos_order1));
              } else {
                $('.membercenter').removeClass('hidden');
                App.msg(res.msg);
              }
              if (!res.TokenTrue) {
                App.msg("Token失效，即将跳转到登录页面", function () {
                  setTimeout(function () {
                    location.href = "../login.html";
                  }, 1000)
                })
              }
            })
          }
        }
      }

    }

  });

  //#############会员充值操作###################//
  //获取会员充值赠送金额
  App.ajax("ss_wx/vip_presenter", "post", {}, function (res) {
    if (res.flag == true) {
      var html = "<option value=''>选择赠送方式</option>";
      res.presenter_details.forEach(function (a, b) {
        html += '<option value="' + a.id + '">' + a.name + '</option>';
      });
      $(".presenterLists").html(html);
    } else {
      App.msg(res.msg);
    }
    if (!res.TokenTrue) {
      App.msg("Token失效，即将跳转到登录页面", function () {
        setTimeout(function () {
          location.href = "../login.html";
        }, 1000)
      })
    }
  });

  // 选择不同的支付方式
  $(".form_HYCZ .CZFSBtns").on("click", ".btn", function () {
    var payid = $(this).data("payid");
    $(this).addClass("active").siblings().removeClass("active");
    if (payid == 1) {
      $(".MM_input").removeClass("hidden");
      $("#MM").val("");
      $(".FKM_input").addClass("hidden");
    } else if (payid == 2 || payid == 3) {
      $(".MM_input").addClass("hidden");
      $(".FKM_input").removeClass("hidden");
      $("#FKM").val("");
    }
  });
  //点击搜索
  $(".form_HYCZ .btn-search").off("click").on("click", function () {
    var HYZH = $("#HYZH").val();
    if (HYZH.length != 11) {
      App.msg("输入会员账号有误，请重新输入");
    } else {
      App.ajax("ss_wx/vip_details", "post", {
        "member_id": HYZH,
      }, function (res) {
        if (res.flag == true) {
          $(".ZHInfo").removeClass("hidden");
          $(".ZHInfo .ZHYE").html(res.member_details.total_money);
          $(".ZHInfo .HYZK").html(res.member_details.discount);
        } else {
          $(".ZHInfo").addClass("hidden");
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    }
  });
  //点击确认
  $(".form_HYCZ .CZ_sure").off("click").on("click", function () {
    var payid = $(".CZFSBtns .active").data("payid");
    var formData = $(".form_HYCZ").serializeArray();
    var obj = {};
    let member_id = false;
    let money = false;
    let MM = false;
    let FKM = false;
    formData.forEach(function (i, v) {
      obj[i.name] = i.value;
      if (i.name == 'member_id') {
        member_id = i.value;
      }
      if (i.name == 'money') {
        money = i.value;
      }
      if (i.name == 'MM') {
        MM = i.value;
      }
      if (i.name == 'FKM') {
        FKM = i.value;
      }
    });

    if (payid == 1) {
      if (!member_id || member_id == '') {
        App.msg('请输入会员账号')
      } else if (!money || money == '') {
        App.msg('请输入充值金额')
      } else if (MM == '') {
        App.msg('请输入密码')
      } else {
        //现金
        let xjpassword = $(".form-group #MM").val();
        $('.showpayinfo').removeClass('hidden');
        App.confirm("请确定充值账号：" + obj.member_id + "？", function () {
          App.ajax("ss_wx/vip_sale_money", "post", {
            'member_id': obj.member_id,
            'money': obj.money,
            'presenter_id': obj.presenter_id,
            'xjpassword': xjpassword
          }, function (res) {
            if (res.flag == true) {
              $('.showpayinfo').addClass('hidden');
              App.msg("充值成功。", function () {
                $(".ZHInfo").addClass("hidden");
                $(".form_HYCZ input").val("");
                $(".presenterLists option:first").prop("selected", true);
              });
              window.samfeng.vipRecharge(JSON.stringify(res.printinfo));
            } else {
              App.msg(res.msg);
            }
            if (!res.TokenTrue) {
              App.msg("Token失效，即将跳转到登录页面", function () {
                setTimeout(function () {
                  location.href = "../login.html";
                }, 1000)
              })
            }
          })
        }, function () {})
      }

    } else {
      //扫码支付
      if (!obj.FKM || obj.FKM == "") {
        App.msg("支付码不能为空!");
        return
      }
      App.confirm("请确定充值账号：" + obj.member_id + "？", function () {
        $("#czloading").modal("show");
        App.ajax("scanQrcodeOrder", "post", {
          'member_id': obj.member_id,
          'money': obj.money,
          'presenter_id': obj.presenter_id,
          'auth_code': obj.FKM,
          'out_trade_no_extend': App.guid(),
          'online_pay_flag': 2,
          'product_name': "member order"
        }, function (res) {
          if (res.return_code == "SUCCESS") {
            App.msg("充值成功。", function () {
              $(".ZHInfo").addClass("hidden");
              $(".form_HYCZ input").val("");
              $(".presenterLists option:first").prop("selected", true);
            })
            $("#czloading").modal("hide");
            window.samfeng.vipRecharge(JSON.stringify(res.printinfo));
          } else {
            App.msg(res.return_msg);
          }
          if (!res.TokenTrue) {
            App.msg("Token失效，即将跳转到登录页面", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      }, function () {})
    }

  });

  //#############会员充值操作###################//

  //添加光标
  clickInput("Discount", "请输入折扣");
  clickInput("MLJE", "0.0");
  clickInput("inputMon", "0.0");
  clickInput("FKMInput", "");
  clickInput("member_id", "");
  clickInput("ZFMM", "");

  //获取会员优惠
  $("#member_id").on("change", function (e) {
    var dishcount = $("#Discount").val();
    var receivMon = $("#receivMon").html();
    if (dishcount > 0 || !$(".showCoupon").hasClass("hidden")) {
      return;
    }
    App.ajax("ss_wx/getVipDiscount", "post", {
      member_id: e.target.value
    }, function (res) {
      if (res.flag == true) {
        if (res.vip_discount != 1) {
          $(".vipCount").removeClass("hidden").html("会员折扣：" + res.vip_discount);
        }
        $("#receivMon").html(((receivMon * res.vip_discount)).toFixed(2));
        $("#inputMon").val(((receivMon * res.vip_discount)).toFixed(2));
      } else {
        App.msg(res.msg);
        $(".vipCount").addClass("hidden");
        $("#receivMon").html((receivMon * 1).toFixed(2));
        $("#inputMon").val((receivMon * 1).toFixed(2));
      }
      if (!res.TokenTrue) {
        App.msg("Token失效，即将跳转到登录页面", function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })

  })

  // 点击输入数字
  function clickInput(input, text) {
    $("#" + input).off("focus").on("focus", function () {
      clickBoard(input, text);
    })
    clickBoard(input, text);
  }
  //付款码
  $("#FKMInput").off("keyup").on('keyup', function (e) {
    if (e.keyCode == 13) {
      $(".board .checkOut").trigger("click");
    }
  })

  //点击数据键盘
  var flag_once1 = true;

  function clickBoard(input, text) {
    $(".Cashier .keyBoard .board").off("click").on("click", ".item", function () {
      var num = $(this).data("num") + "";
      if (num !== "checkOut") {
        $("#" + input).focus();
      }
      if (num == "empty") {
        $("#" + input).val("").trigger("input");
      } else if (num == "del") {
        var selecStart = $("#" + input).get(0).selectionStart;
        var curVal = $("#" + input).val();
        if (selecStart - 1 >= 0) {
          $("#" + input).val(curVal.slice(0, selecStart - 1) + curVal.slice(selecStart)).trigger("input");
          $("#" + input).get(0).selectionStart = selecStart - 1;
          $("#" + input).get(0).selectionEnd = selecStart - 1;
        }
      } else if (num == "checkOut") {
        if (flag_once1) {
          flag_once1 = false;
          setTimeout(function () {
            flag_once1 = true;
          }, 3000);
          var pay_info = [];
          curTable.cart.forEach(function (v, i) {
            var obj = {
              p_id: v.p_id,
              p_num: v.num,
              name: v.name,
              temporary_flag: v.temporary_flag,
              c_id: v.c_id,
              price: v.price,
              print: (v.print ? v.print : []),
              uom: v.uom,
              cuisine: v.tastes ? v.tastes : [],
              pnotes: '',
              sdnotes: '',
              local_printer: v.local_printer,
              printer_position: v.printer_position,
            };
            if (v.combo_details && v.combo_details.length > 0) {
              obj.combo_details = v.combo_details1;
            } else {
              obj.combo_details = [];
            }
            pay_info.unshift(obj);
          });
          var card_details = "";
          if (!$(".showCoupon").hasClass("hidden")) {
            card_details = $(".showCoupon .couponInfo").data("couponinfo");
          }
          var pay_id = $(".Cashier .payLists ul li.active").data("paytype");

          //点击确定收银
          // if (payCode&&!curTable.order_id) {
          // if (pay_id.code == "TSCH" || pay_id.code == "YHKZF") {
          if (pay_id.type == "cash") {
            if (!curTable.order_id) {
              var pay_methods = [{
                "pay_id": pay_id.id,
                "money": $("#inputMon").val(),
                'paymethodname': pay_id.code == "TSCH" ? '现金支付' : '银行卡支付'
              }];
              if (MorepayArr.length > 0) {
                MorepayArr.forEach(function (v) {
                  pay_methods.push({
                    "pay_id": v.id,
                    "money": v.money,
                    'paymethodname': v.name
                  })
                })
              }
              var xj_pos_order = {
                "pay_flag": 0,
                "direct_order": true, //用于安卓打印
                "pos_order": JSON.stringify({
                  "order_id": App.guid(),
                  "origin_reference": curTable.origin_reference ? curTable.origin_reference : "",
                  "date_order": App.formatDateTime(new Date()),
                  "pay_method": pay_methods,
                  "card_details": card_details,
                  "discount": $("#Discount").val(),
                  "need_to_pay": $("#receivMon").html(),
                  "customer_pay": $("#inputMon").val(),
                  "moling": "",
                  "zhaoLing": (pay_id.code == "TSCH" ? $("#ZLMon").html() : ""),
                  "pay_info": pay_info,
                  "p_total": curTable.totalInfo.totalMon,
                  "floor_id": curTable.floor_id,
                  "table_id": curTable.table_id,
                  "table_name": curTable.name,
                  "note": curTable.ZDBZ ? curTable.ZDBZ : "",
                  "pay_note": $("#comment").val(),
                  // "print_num": localStorage.getItem("print_num"),
                })
              };
              if ($("#inputMon").val() * 1 >= 0) {
                App.ajax("ss_wx/hzg_orders_and_pay", "post", xj_pos_order, function (res) {
                  if (res.flag == true) {
                    let f_pos_order = JSON.parse(xj_pos_order.pos_order);
                    f_pos_order.f_date = res.pay_date;
                    f_pos_order.order_sequence = res.order_sequence;
                    xj_pos_order.pos_order = JSON.stringify(f_pos_order);
                    localStorage.removeItem("tableInfos");
                    localStorage.removeItem("curTable");
                    localStorage.removeItem("payCode");
                    App.msg("支付成功", function () {
                      $('#loading').modal('hide');
                      setTimeout(function () {
                        location.href = "../pages/Table.html";
                      }, 1000);
                    });
                    window.samfeng.OrderPay(JSON.stringify(xj_pos_order));
                  } else {
                    flag_once1 = true;
                    App.msg(res.msg);
                  }
                  if (!res.TokenTrue) {
                    App.msg("Token失效，即将跳转到登录页面", function () {
                      setTimeout(function () {
                        location.href = "../login.html";
                      }, 1000)
                    })
                  }
                })
              }
            } else {
              if ($("#inputMon").val() * 1 >= 0) {
                var pay_methods1 = [{
                  "pay_id": pay_id.id,
                  "money": $("#inputMon").val(),
                  "paymethodname": pay_id.name
                }];
                if (MorepayArr.length > 0) {
                  MorepayArr.forEach(function (v) {
                    pay_methods1.push({
                      "pay_id": v.id,
                      "money": v.money,
                      'paymethodname': v.name
                    })
                  })
                }
                var xj_pos_order1 = {
                  "pay_flag": 0,
                  "direct_order": false, //用于安卓打印
                  "pos_order": JSON.stringify({
                    "order_id": curTable.order_id ? curTable.order_id : App.guid(),
                    "origin_reference": curTable.origin_reference ? curTable.origin_reference : "",
                    "pay_method": pay_methods1,
                    "card_details": card_details,
                    "discount": $("#Discount").val(),
                    "need_to_pay": $("#receivMon").html(),
                    "customer_pay": $("#inputMon").val(),
                    "moling": "",
                    "zhaoLing": (pay_id.code == "TSCH" ? $("#ZLMon").html() : ""),
                    "pay_info": pay_info,
                    "p_total": curTable.totalInfo.totalMon,
                    "floor_id": curTable.floor_id,
                    "table_id": curTable.table_id,
                    "table_name": curTable.name,
                    "note": curTable.ZDBZ ? curTable.ZDBZ : "",
                    "pay_note": $("#comment").val(),
                    "m_date": curTable.m_date,
                    "f_date": curTable.f_date,
                    // "print_num": localStorage.getItem("print_num"),
                  })
                };
                App.ajax("ss_wx/hzg_orders_pay", "post", xj_pos_order1, function (res) {
                  flag_once = true;
                  if (res.flag == true) {
                    var change_pos_order = JSON.parse(xj_pos_order1.pos_order);
                    change_pos_order.origin_reference = res.origin_reference;
                    change_pos_order.f_date = res.pay_date;
                    xj_pos_order1.pos_order = JSON.stringify(change_pos_order);
                    localStorage.removeItem("tableInfos");
                    localStorage.removeItem("curTable");
                    localStorage.removeItem("payCode");
                    App.msg("支付成功", function () {
                      $('#loading').modal('hide');
                      setTimeout(function () {
                        location.href = "../pages/Table.html";
                      }, 1000);
                    });
                    window.samfeng.OrderPay(JSON.stringify(xj_pos_order1));
                  } else {
                    flag_once1 = true;
                    App.msg(res.msg);
                  }
                  if (!res.TokenTrue) {
                    App.msg("Token失效，即将跳转到登录页面", function () {
                      setTimeout(function () {
                        location.href = "../login.html";
                      }, 1000)
                    })
                  }
                })
              }
            }
          }
        }

      } else if (num.indexOf("元") > -1) {
        var mon = parseFloat(num);
        $("#" + input).val(mon).trigger("input");
      } else {
        var inputVal = $("#" + input).val();
        $("#" + input).val(inputVal + num).trigger("input");
      }
    })
  }
})